import './index.scss'
import {
    Breadcrumb, Button, Space, DatePicker, Form, Input, Select, Table, Col, Row, Modal, Image, Tag
} from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { useEffect, useState } from 'react';
import { useNavigate } from "react-router-dom"
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import moment from 'moment';

import time from '../../../utils/formatDay-wl'

import { getGoods, delGoods, shelvesGoods } from '../../../api/WL/goods'

const GoodsManagement = () => {
    const [list, setList] = useState({});

    const [data, setData] = useState([]);

    //表格数据初始化
    const getGoodsData = () => {
        getGoods().then((res) => {
            console.log(res.data);
            if (res.code === 200) {
                let _data = res.data;
                if (_data.length > 0) {
                    _data.forEach(item => {
                        item.onTime = moment(item.onTime).format('YYYY-MM-DD mm:ss')
                    });
                }
                setData(_data);
            }
        })
    }
    useEffect(() => {
        getGoodsData()
    }, [])

    //搜索的表单
    const [form] = Form.useForm();

    //搜索中点击今日、昨日。。。的按钮传值
    const date = (v) => {
        let list2 = { m: v }
        setList({ ...list2 })
    }

    //点击搜索按钮，执行的函数
    const onFinish = (values) => {
        // console.log('Finish:', values);
        if (values.Time) {
            let time1 = moment(values.Time[0]).format('YYYY/MM/DD');
            let time2 = moment(values.Time[1]).format('YYYY/MM/DD');
            delete values.Time;//删除values里的Time属性
            // console.log(values, 11);
            values.startOnTime = time1;//增加values里的startOnTime属性
            values.endOnTime = time2;//增加values里的endOnTime属性
        } else {
            delete values.Time;//删除values里的Time属性
            values.startOnTime = undefined;//增加values里的startOnTime属性
            values.endOnTime = undefined;//增加values里的endOnTime属性
        }
        // console.log(values, 22);
        let sad = { ...values }
        sad.timeType = list.m;
        console.log(sad, 33);

        getGoods(sad).then((res) => {
            console.log(res);
            if (res.code === 200) {
                let _data = res.data;
                if (_data.length > 0) {
                    _data.forEach(item => {
                        item.onTime = time(item.onTime)
                    });
                }
                setData(_data);
            }
        })
    };

    //日期选择器，国际化
    const { RangePicker } = DatePicker;

    //表格
    const columns = [
        {
            title: '商品信息',
            key: 'goodsName',
            render: (_, record) => (
                <Space size="middle">
                    <Image
                        width={70}
                        src={'http://192.168.221.234:8011/' + record.picture}
                    />
                    <p style={{ marginTop: '20px' }}>{record.goodsName}</p>
                </Space>
            ),
        },
        {
            title: '商品价格（元）',
            key: 'price',
            dataIndex: 'price',
        },
        {
            title: '销售量',
            key: 'sales',
            dataIndex: 'sales',
        },
        {
            title: '商品状态',
            key: 'onState',
            render: (_, record) => {
                if (record.onState === '1') {
                    return <Tag color="default">已下架</Tag>
                }
                if (record.onState === '2') {
                    return <Tag color="success">已上架</Tag>
                }
                if (record.onState === '3') {
                    return <Tag color="processing">待上架</Tag>
                }
            }
        },
        {
            title: '上架时间',
            key: 'onTime',
            dataIndex: 'onTime',
        },
        {
            title: '排序号',
            key: 'sortingId',
            dataIndex: 'sortingId',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button type='link' onClick={() => EditGoods(record.goodsId)}>编辑</Button>
                    <Button type='link' style={{ display: record.onState === '2' ? 'block' : 'none' }} onClick={() => showConfirm(record.goodsId)}>下架</Button>
                    <Button type='link' onClick={() => showDeleteConfirm(record.goodsId)}>删除</Button>
                </Space>
            ),
        },
    ];

    //表格的页码
    const showTotal = (total) => `数量 ${total} 条`;

    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        }
    };
    const [selectionType, setSelectionType] = useState('checkbox');

    //下架的模态框
    const { confirm } = Modal;

    const showConfirm = (id) => {
        console.log(id);
        confirm({
            title: '下架商品',
            icon: <ExclamationCircleOutlined />,
            content: '确定下架此商品吗?',
            okText: '确认',
            cancelText: '取消',
            centered: true,
            onOk() {
                shelvesGoods(id).then((res) => {
                    console.log(res);
                    if (res.code === 200) {
                        getGoodsData()
                    }
                })
            },

            onCancel() {
                console.log('Cancel');
            },
        });
    };

    //删除的模态框
    const showDeleteConfirm = (id) => {
        console.log(id);
        confirm({
            title: '删除后将无法恢复此商品信息，确定删除吗?',
            icon: <ExclamationCircleOutlined />,
            content: '删除商品',
            okText: '确认',
            cancelText: '取消',
            centered: true,

            onOk() {
                delGoods(id).then((res) => {
                    console.log(res);
                    if (res.code === 200) {
                        getGoodsData();
                    }
                })
            },

            onCancel() {
                console.log('Cancel');
            },
        });
    };

    //修改商品管理的页面跳转
    const navigate = useNavigate();
    const EditGoods = (values) => {
        navigate('/home/editGoods', { state: values });
    }

    //新增商品管理的页面跳转
    const addGoods = () => {
        navigate('/home/addGoods');
    }

    return <div className='mainGoods'>
        <div className='headerGoods'>
            <div className='headerGoodsTop'>
                <div>
                    <Breadcrumb>
                        <Breadcrumb.Item>实物商品</Breadcrumb.Item>
                        <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <h2>商品管理</h2>
            </div>
            <hr />
            <div className='headerGoodsBottom'>
                <Form form={form} name="horizontal_login" onFinish={onFinish} className='formSearch'>
                    <Row justify='start' gutter={250}>
                        <Col>
                            <Form.Item
                                label="商品状态"
                                name="onState"
                            >
                                <Select placeholder="请选择课程状态">
                                    <Select.Option>全部</Select.Option>
                                    <Select.Option value="1">已下架</Select.Option>
                                    <Select.Option value="2">已上架</Select.Option>
                                    <Select.Option value="3">待上架</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col>
                            <Form.Item
                                label="商品名称"
                                name="goodsName"
                            >
                                <Input type="text" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={20}>
                        <Col>
                            <Form.Item
                                label="上架日期"
                                name="Time"
                            >

                                <RangePicker locale={locale} />

                            </Form.Item>
                        </Col>
                        <Col>
                            <Form.Item
                                name="timeType"
                            >
                                <Button type="text" onClick={() => date('1')}>今日</Button>
                            </Form.Item>
                        </Col>
                        <Col>
                            <Form.Item
                                name="timeType"
                            >
                                <Button type="text" onClick={() => date('2')}>昨日</Button>
                            </Form.Item>
                        </Col>
                        <Col>
                            <Form.Item
                                name="timeType"
                            >
                                <Button type="text" onClick={() => date('3')}>最近7天</Button>
                            </Form.Item>
                        </Col>
                        <Col>
                            <Form.Item
                                name="timeType"
                            >
                                <Button type="text" onClick={() => date(4)}>最近30天</Button>
                            </Form.Item>
                        </Col>
                        <Col>
                            <Form.Item shouldUpdate style={{ position: 'absolute', left: '240px', top: 0 }}>
                                {() => (
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                    >
                                        查询
                                    </Button>
                                )}
                            </Form.Item>
                        </Col>
                        <Col>
                            <Form.Item shouldUpdate style={{ position: 'absolute', left: '300px', top: 0 }}>
                                {() => (
                                    <Button onClick={() => {
                                        getGoodsData()
                                        return form.resetFields();
                                    }}>重置</Button>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
        </div>

        <div className='sectionGoods'>
            <div className='sectionItem1'>
                <p>商品列表</p>
                <div>
                    <Button type="primary" icon={<PlusOutlined />} onClick={addGoods}>
                        新建
                    </Button>
                </div>
            </div>
            <div className='sectionItem2'>
                <Table
                    rowKey={(record) => record.goodsId}
                    rowSelection={{
                        type: selectionType,
                        ...rowSelection,
                    }}
                    columns={columns}
                    dataSource={data}
                    pagination={{
                        total: data.length,
                        showTotal: showTotal,
                        showSizeChanger: true,
                        showQuickJumper: true,
                    }}
                />

            </div>
        </div>
    </div>
}

export default GoodsManagement;